//
// Created by 33145 on 2023/6/7.
//

#ifndef ROCKET_STRING_CODER_H
#define ROCKET_STRING_CODER_H

#include <utility>

#include "abstract_coder.h"
#include "abstract_protocol.h"

namespace rocket {
  class StringProtocol : public AbstractProtocol {

  public:
    explicit StringProtocol(std::string  s = "") : info(std::move(s)) {}
    std::string info;

  };

  class StringCoder : public AbstractCoder {
    // 将 message 对象转化为字节流，写入到 buffer
    void encode(std::vector<AbstractProtocol::ptr>& messages, TCPBuffer::ptr out_buffer) override {
      for (const auto & message : messages) {
        std::shared_ptr<StringProtocol> msg = std::dynamic_pointer_cast<StringProtocol>(message);
        out_buffer->writeToBuffer(msg->info.c_str(), msg->info.size());
      }
    }

    // 将 buffer 里面的字节流转换为 message 对象
    void decode(std::vector<AbstractProtocol::ptr>& out_messages, TCPBuffer::ptr buffer) override {
      std::vector<char> re;
      buffer->readFromBuffer(re, buffer->readAble());
      std::string info;
      for (char i : re) {
        info += i;
      }

      std::shared_ptr<StringProtocol> msg = std::make_shared<StringProtocol>();
      msg->info = info;
      msg->_msg_id = "123456";
      out_messages.push_back(msg);
    }

  };
}

#endif //ROCKET_STRING_CODER_H
